package com.example.educationblockchain.config;

import com.example.educationblockchain.mapper.StudentLoginMapper;
import com.example.educationblockchain.model.AdminLogin;
import com.example.educationblockchain.mapper.AdminLoginMapper;
import com.example.educationblockchain.model.StudentLogin;
import com.example.educationblockchain.util.AdminToken;
import com.example.educationblockchain.util.StudentToken;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.Map;

public class AdminRealm extends AuthorizingRealm {

    @Autowired
    AdminLoginMapper adminLoginMapper;

    @Autowired
    StudentLoginMapper studentLoginMapper;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        Map map = (Map)principalCollection.getPrimaryPrincipal();

        System.out.println(map);

        String perm = map.get("perms").toString();

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        info.addStringPermission(perm);

        // 授权的时候执行
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 认证的时候执行
        if(authenticationToken instanceof AdminToken){
            UsernamePasswordToken userToken= (UsernamePasswordToken) authenticationToken;

            String id = userToken.getUsername();

            AdminLogin adminLogin = adminLoginMapper.selectById(id);

            if(adminLogin==null){
                return null;
            }

            Map<String,String> map = new HashMap<>();
            map.put("id",id);
            map.put("perms","admin:all");
            map.put("roles","admin");

            return new SimpleAuthenticationInfo(map,userToken.getPassword(),"");
        }else if(authenticationToken instanceof StudentToken){
            UsernamePasswordToken userToken= (UsernamePasswordToken) authenticationToken;

            String id = userToken.getUsername();

            StudentLogin studentLogin = studentLoginMapper.selectById(id);

            if(studentLogin==null){
                return null;
            }

            Map<String,String> map = new HashMap<>();
            map.put("id",id);
            map.put("perms","student:all");

            return new SimpleAuthenticationInfo(map,userToken.getPassword(),"");
        }else{
            return null;
        }

    }
}
